﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessPlatform.Core.Database;
using System.Data.Common;
using System.Data;

namespace BusinessPlatform.Core.BusinesObjectType
{
    internal static class GetObjectValue
    {
        /// <summary>
        /// 获取对象的唯一主键
        /// </summary>
        /// <param name="db"></param>
        /// <param name="DataEntity"></param>
        /// <returns></returns>
        public static int GetUniqueKey(IDatabase db, IDataStructure DataEntity)
        {
            int AutoKey = default(int);
            string QueryString = "SELECT AUTOKEY FROM [BUSINESSOBJECT] WITH (UPDLOCK) WHERE OBJECTCODE = @OBJECTCODE";
            var GetParameters = new List<DbParameter>();
            GetParameters.Add(db.AddParameter("OBJECTCODE", DbType.String, DataEntity.ObjectType));
            object result = db.ExceuteScalar(QueryString, GetParameters);
            if (result != null)
            {
                AutoKey = Convert.ToInt32(result);
            }
            else
            {
                throw (new Exception("[" + DataEntity.ObjectType + "]对象获取编号失败！"));
            }
            QueryString = "UPDATE [BUSINESSOBJECT] SET AUTOKEY = AUTOKEY + 1 WHERE OBJECTCODE = @OBJECTCODE";
            var SetParameters = new List<DbParameter>();
            SetParameters.Add(db.AddParameter("OBJECTCODE", DbType.String, DataEntity.ObjectType));
            var Affect = db.ExceuteNonQuery(QueryString, SetParameters);
            if (Affect <= 0)
            {
                throw (new Exception("[" + DataEntity.ObjectType + "]对象更新编号失败！"));
            }
            return AutoKey;
        }
    }
}
